<template>
  <div class="app-container article-container">
    <div class="content">
      <el-card shadow="never" style="margin: 0 0 20px">文章列表</el-card>
      <div class="article-list">
        <el-link
          v-for="(item, key) in articleList"
          :key="key"
          @click.prevent="redirectDetail(item)"
        >
          <el-card shadow="never">
            <articleCover v-model="item.cover" width="220px" height="150px" />
            <div class="list-content">
              <header>{{ item.heading }}</header>
              <p>{{ item.content.replace(/<[^>]+>/g, "").slice(0, 170) }}...</p>
              <p>
                {{ getCategory(item.categoryId) }}&nbsp;
                {{ item.uploadTime?.substring(0, 10) }}
              </p>
            </div>
          </el-card>
        </el-link>
      </div>

      <div class="pagination p1 mb-5 mt-5" style="background-color: #fff">
        <el-pagination
          layout="prev, pager, next, total"
          :pager-count="5"
          :total="pageParam.total"
          :default-page-size="pageParam.pageSize"
          v-model:current-page="pageParam.page"
          background
          @current-change="pageChange"
        />
      </div>
    </div>
    <el-affix class="sidebar" :offset="100" :z-index="200">
      <el-card class="sidebar">sidebar右侧导航</el-card>
    </el-affix>
  </div>
</template>

<script setup lang="ts">
import articleCover from "@/components/articleCover/index.vue";
import articleAPI, { type ArticleResult } from "@/api/article";
import categoryAPI, { type CategoryResult } from "@/api/category";
import { backtopClick } from "@/utils/index";
import router from "@/router";

defineOptions({
  name: "",
});

const articleList = ref<ArticleResult[]>();
const categoryList = ref<CategoryResult[]>();
const pageParam = ref<PageQuery & pageCount>({
  page: 1,
  pageSize: 15,
  total: 0,
});
//文章列表功能
const getArticleList = async () => {
  const result = await articleAPI.getArticle(pageParam.value);
  articleList.value = result.rows;
  pageParam.value.total = result.total;
};
//类别功能
const getCategoryList = async () => {
  const data = await categoryAPI.getCategoryList({ page: 1, pageSize: 999 });
  categoryList.value = data.rows;
};
const getCategory = (id: number) => {
  const filter = categoryList.value?.filter((item: CategoryResult) => {
    return item.id === id;
  });
  return filter ? filter[0].name : null;
};

const redirectDetail = (data: ArticleResult) => {
  router.push({ path: "/user/study/article/" + data.id });
};

//分页功能
const pageChange = () => {
  getArticleList();
  backtopClick();
};

onMounted(() => {
  getArticleList();
  getCategoryList();
});
</script>

<style lang="scss" scoped>
.sidebar {
  border-radius: 10px;
}
</style>
